package com.cqxyd.smartsite.controller.vs1;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.cqxyd.smartsite.pojo.CraneRecord;
import com.cqxyd.smartsite.pojo.Heartbeat;
import com.cqxyd.smartsite.pojo.LifterRecord;
import com.cqxyd.smartsite.service.DeviceInfoService;
import com.cqxyd.smartsite.service.ProgramInfoService;
import com.cqxyd.smartsite.service.UploadRecordService;
import com.cqxyd.smartsite.util.JSONResult;
import com.cqxyd.smartsite.util.PostHelper;
import com.cqxyd.smartsite.version.ApiVersion;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

@RestController
@ApiVersion(1)
@RequestMapping(value = "{version}/api/lifter")
@Api(value = "升降机信息接口", tags = "升降机信息接口")
public class LifterRecordController1 {
    private final Logger logger = LoggerFactory.getLogger(LifterRecordController1.class);
    @Autowired
    private PostHelper postHelper;
    @Autowired
    private UploadRecordService uploadRecordService;
    @Autowired
    private ProgramInfoService programInfoService;
    @Autowired
    private DeviceInfoService deviceInfoService;

    @PostMapping(value = "record")
    @ApiOperation(value = "上传升降机信息", notes = "上传升降机信息", produces = "application/json")
    @ApiImplicitParams
            ({
                    @ApiImplicitParam(name = "registNo", value = "升降机编号", required = true, paramType = "query", dataType = "String"),
                    @ApiImplicitParam(name = "serialNo", value = "主机（黑匣子）编号", required = true, paramType = "query", dataType = "String"),
                    @ApiImplicitParam(name = "recordTime", value = "采集时间（yyyy-MM-dd HH:mm:ss）", required = true, paramType = "query", dataType = "String"),
                    @ApiImplicitParam(name = "startTime", value = "工作循环开始时间（yyyy-MM-dd HH:mm:ss）", required = true, paramType = "query", dataType = "String"),
                    @ApiImplicitParam(name = "stopTime", value = "工作循环终止时间（yyyy-MM-dd HH:mm:ss）", required = true, paramType = "query", dataType = "String"),
                    @ApiImplicitParam(name = "startHeight", value = "本次起升起点高度", required = true, paramType = "query", dataType = "double"),
                    @ApiImplicitParam(name = "stopHeight", value = "本次起升终点高度", required = true, paramType = "query", dataType = "double"),
                    @ApiImplicitParam(name = "speed", value = "本次起升平均速度", required = true, paramType = "query", dataType = "double"),
                    @ApiImplicitParam(name = "load", value = "本次载重", required = true, paramType = "query", dataType = "double"),
                    @ApiImplicitParam(name = "loadPercent", value = "本次载重百分比", required = true, paramType = "query", dataType = "double"),
                    @ApiImplicitParam(name = "direction", value = "本次起升方向(1:上升,2:下降)", required = true, paramType = "query", dataType = "int"),
                    @ApiImplicitParam(name = "driverId", value = "驾驶员身份证号", required = true, paramType = "query", dataType = "String"),
                    @ApiImplicitParam(name = "driverLicence", value = "驾驶员证书编号", required = true, paramType = "query", dataType = "String"),
                    @ApiImplicitParam(name = "driverName", value = "驾驶员姓名", required = true, paramType = "query", dataType = "String"),
                    @ApiImplicitParam(name = "status", value = "状态, 0：正常 1：预警 2：报警 3：违章 4：其他", required = true, paramType = "query", dataType = "String"),
                    @ApiImplicitParam(name = "message", value = "预警/报警/违章消息，非正常状态时必须传入", required = false, paramType = "query", dataType = "String")
            })
    public JSONResult<String> postElevator(@PathVariable("version") String version, String registNo, String serialNo, String recordTime, String startTime, String stopTime,
                                           Double startHeight, Double stopHeight, Double speed, Double load, Double loadPercent, Integer direction, String driverId,
                                           String driverLicence, String driverName, String status, String message) {

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            List<String> keyAndSecret = programInfoService.getKeyAndSecret(serialNo);
            if (keyAndSecret == null) {
                return JSONResult.errorMsg("设备未注册，获取项目信息失败");
            }
            if (!"0".equals(status) && StringUtils.isEmpty(message)) {
                return JSONResult.errorMsg("预警/报警/违章消息，非正常状态时必须传入");
            }
            Date realRecordTime = sdf.parse(recordTime);

            List<LifterRecord> list = new ArrayList<>();
            LifterRecord record = new LifterRecord();
            record.setRegistNo(registNo);
            record.setSerialNo(serialNo);
            record.setRecordTime(realRecordTime);
            record.setStartTime(sdf.parse(startTime));
            record.setStopTime(sdf.parse(stopTime));
            record.setStartHeight(startHeight);
            record.setStopHeight(stopHeight);
            record.setSpeed(speed);
            record.setLoad(load);
            record.setLoadPercent(loadPercent);
            record.setDirection(direction);
            record.setDriverId(driverId);
            record.setDriverLicence(driverLicence);
            record.setDriverName(driverName);
            record.setStatus(status);
            record.setMessage(message);

            int recordId = uploadRecordService.insertAndGetId(serialNo, realRecordTime, record.toString(), "升降机信息");
            if (recordId == 0) {
                String errorInfo = "保存升降机信息上传记录出错：" + record.toString();
                logger.error(errorInfo);
                return JSONResult.errorMsg(errorInfo);
            } else {
                record.setSourceId(String.valueOf(recordId));
            }
            list.add(record);
            return postHelper.postLifterRecord(keyAndSecret.get(0), keyAndSecret.get(1), list);
        } catch (ParseException e) {
            e.printStackTrace();
            return JSONResult.errorMsg("时间转换异常，请确认格式为：yyyy-MM-dd HH:mm:ss");
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage());
            return JSONResult.errorMsg("上传升降机信息失败:" + e.getMessage());
        }
    }

    @PostMapping(value = "heartbeat")
    @ApiOperation(value = "上传升降机心跳信息", notes = "心跳固定每10秒上传一次，平台校验与上次收到心跳的时间差，如果小于10s,则视为此次数据无效，如果大于等于10s则将设备在线时间加10s并更新最新心跳时间为此次收到心跳的时间。", produces = "application/json")
    @ApiImplicitParams
            ({
                    @ApiImplicitParam(name = "registNo", value = "升降机编号", required = true, paramType = "query", dataType = "String"),
                    @ApiImplicitParam(name = "serialNo", value = "主机（黑匣子）编号", required = true, paramType = "query", dataType = "String"),
                    @ApiImplicitParam(name = "recordTime", value = "采集时间（yyyy-MM-dd HH:mm:ss）", required = true, paramType = "query", dataType = "String")
            })
    public JSONResult<String> postHeartbeat(@PathVariable("version") String version, String registNo, String serialNo, String recordTime) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            List<String> keyAndSecret = programInfoService.getKeyAndSecret(serialNo);
            if (keyAndSecret == null) {
                return JSONResult.errorMsg("设备未注册，获取项目信息失败");
            }
            Date realRecordTime = sdf.parse(recordTime);
            Heartbeat heartbeat = new Heartbeat();
            heartbeat.setRegistNo(registNo);
            heartbeat.setSerialNo(serialNo);
            heartbeat.setSendTime(realRecordTime);

            try {
                //int affectRowCount = uploadRecordService.insert(serialNo, realRecordTime, heartbeat.toString(), "升降机心跳信息");

                int affectRowCount = deviceInfoService.updateLastHeartbeatTime(serialNo, realRecordTime);
                if (affectRowCount == 0) {
                    logger.error("更新设备最后心跳时间出错：" + serialNo);
                }
            } catch (Exception e) {
                e.printStackTrace();
                logger.error(e.getMessage());
            }

            return postHelper.postLifterHeartbeat(keyAndSecret.get(0), keyAndSecret.get(1), heartbeat);
        } catch (ParseException e) {
            e.printStackTrace();
            return JSONResult.errorMsg("时间转换异常，请确认格式为：yyyy-MM-dd HH:mm:ss");
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage());
            return JSONResult.errorMsg("上传塔吊心跳失败:" + e.getMessage());
        }
    }
}
